<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="username" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="btn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(val, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ val.name }}</td>
          <td>{{ val.age }}</td>
          <td>{{ val.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          name: "Tom",
          age: 19,
          sex: "男",
        },
        {
          name: "Jone",
          age: 21,
          sex: "女 ",
        },
      ],
      username: "",
      age: "",
      sex: "",
      isshow: true, //定义是否为添加修改
      i: "", //定义数组的索引
    };
  },
  methods: {
    btn() {
      if (this.username == "" || this.age == "" || this.sex == "") {
        alert("请输入内容");
      } else if (this.isshow) {
        this.arr.push({
          name: this.username,
          age: this.age,
          sex: this.sex,
        });
      } else if (this.isshow == false) {
        this.arr[this.i].name = this.username;
        this.arr[this.i].age = this.age;
        this.arr[this.i].sex = this.sex;
        this.isshow = true; // 修改之后把isshow变为true 按钮变为添加状态
        this.username = ""; //修改之后把表单内容清空
        this.age = "";
        this.sex = "";
      }
    },
    del(index) {
      this.arr.splice(index, 1);
    },
    edit(index) {
      this.username = this.arr[index].name;
      this.age = this.arr[index].age;
      this.sex = this.arr[index].sex;
      this.isshow = false;
      this.i = index; // 把索引赋值给全局变量
    },
  },
};
</script>